<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Kowcore
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: Core.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Kowcore
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Kowcore_Api_Core extends Core_Api_Abstract {
	
	public function formatAddress($values) {
		$data = array ();
		
		if ($values ['address']) {
			$data [] = $values ['address'];
		}
		
		if ($values ['city']) {
			$data [] = $values ['city'];
		}
		
		if ($values ['state']) {
			$data [] = $values ['state'];
		}
		
		if ($values ['country']) {
			$data [] = $values ['country'];
		}
		
		return implode ( ', ', $data );
	}
	
	public function getGmapJs($setting) {
		$apiKey = $this->getApiKey ( $setting );
		return '<script src="http://maps.google.com/maps/api/js?sensor=false&language=en&file=api&v=3&key=' . $apiKey . '" type="text/javascript"></script>';
	}
	
	public function getLocationInfo($address, $setting) {
		$address = rawurlencode ( $address );
		$url = $this->getGmapUrl ( $address, $setting );
		$result = file_get_contents ( $url );
		
		return $result;
	}
	
	public function getGmapUrl($address, $setting) {
		$apiKey = $this->getApiKey ( $setting );
		return 'http://maps.google.com/maps/geo?&q=' . $address . '&output=json&oe=utf8&key=' . $apiKey;
	}
	
	public function getApiKey($setting) {
		return Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( $setting, '' );
	}
	
	public function getMapBounds($markers) {
		$minLat = 200;
		$maxLat = - 200;
		$minLng = 200;
		$maxLng = - 200;
		
		if (count ( $markers ) == 0) {
			return array ();
		} elseif (count ( $markers ) == 1) {
			$marker = $markers [0];
			$minLat = $maxLat = $marker ['latitude'];
			$minLng = $maxLng = $marker ['longitude'];
		} else {
			foreach ( $markers as $marker ) {
				if (empty ( $marker ['longitude'] ) || empty ( $marker ['latitude'] ))
					continue;
				
				if ($marker ['longitude'] <= $minLng) {
					$minLng = $marker ['longitude'];
				}
				if ($marker ['longitude'] >= $maxLng) {
					$maxLng = $marker ['longitude'];
				}
				if ($marker ['latitude'] <= $minLat) {
					$minLat = $marker ['latitude'];
				}
				if ($marker ['latitude'] >= $maxLat) {
					$maxLat = $marker ['latitude'];
				}
			}
		}
		
		if ($minLat == $maxLat && $minLng == $maxLng) {
			$minLat -= 0.0009;
			$maxLat += 0.0009;
			$minLng -= 0.0009;
			$maxLng += 0.0009;
		}
		
		$mapCenterLat = ( float ) ($minLat + $maxLat) / 2;
		$mapCenterLng = ( float ) ($minLng + $maxLng) / 2;
		
		if ($minLat == 200 || $maxLat == - 200 || $minLng == 200 || $maxLng == - 200) {
			$minLat = '';
			$maxLat = '';
			$minLng = '';
			$maxLng = '';
			$mapCenterLat = '';
			$mapCenterLng = '';
		}
		
		return array ('min_lat' => $minLat, 'max_lat' => $maxLat, 'min_lng' => $minLng, 'max_lng' => $maxLng, 'map_center_lat' => $mapCenterLat, 'map_center_lng' => $mapCenterLng );
	}
	
	public function getNote(Core_Model_Item_Abstract $item) {
		$table = Engine_Api::_ ()->getDbTable ( 'notes', 'kowcore' );
		$select = $table->select ()->where ( 'object_id = ?', $item->getIdentity () )->where ( 'object_type = ?', $item->getType () );
		
		return $table->fetchRow ( $select );
	}
	
	public function postNote(Core_Model_Item_Abstract $item, $text = '') {
		$table = Engine_Api::_ ()->getDbTable ( 'notes', 'kowcore' );
		$note = $this->getNote ( $item );
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		
		if (! $viewer->getIdentity ()) {
			return false;
		}
		
		if (! $note) {
			$note = $table->createRow ();
			$note->creation_date = date ( 'Y-m-d H:i:s' );
		}
		
		$note->note = $text;
		$note->object_type = $item->getType ();
		$note->object_id = $item->getIdentity ();
		$note->user_id = $viewer->getIdentity ();
		$note->modified_date = date ( 'Y-m-d H:i:s' );
		$note->save ();
		
		return $note;
	}
	
	public function ofr() {
		$request = Zend_Controller_Front::getInstance ()->getRequest ();
		
		$guid = $request->getParam ( 'guid', '' );
		$type = $request->getParam ( 'type', $request->getParam ( 'object_type', '' ) );
		$id = $request->getParam ( 'id', $request->getParam ( 'object_id', 0 ) );
		
		if ($type && $id) {
			return Engine_Api::_ ()->getItem ( $type, $id );
		}
		
		if ($guid) {
			return Engine_Api::_ ()->getItemByGuid ( $guid );
		}
		
		return false;
	}
	
	public function strToSlug($text) {
		$text = preg_replace ( '~[^\\pL\d]+~u', '-', $text );
		$text = trim ( $text, '-' );
		$text = iconv ( 'utf-8', 'us-ascii//TRANSLIT', $text );
		$text = strtolower ( $text );
		$text = preg_replace ( '~[^-\w]+~', '', $text );
		
		if (empty ( $text )) {
			return 'n-a';
		}
		
		return $text;
	}
	
	public function getTagCloud(Core_Model_Item_Abstract $subject, $where = '') {
		$table = $subject->getTable ();
		$db = $table->getAdapter ();
		$select = $db->select ();
		
		$type = $subject->getType ();
		//    $name = $table->info('name');
		//    $primary = array_shift($table->info('primary'));
		

		$prefix = $table->getTablePrefix ();
		
		$select->from ( $prefix . 'core_tagmaps', array ('tag_id', 'item_id' => $prefix . 'core_tagmaps.resource_id', 'freq' => 'COUNT(' . $prefix . 'core_tagmaps.tag_id)' ) )->joinLeft ( $prefix . 'core_tags', $prefix . 'core_tagmaps.tag_id = ' . $prefix . 'core_tags.tag_id', array ('text' ) )->//      ->joinLeft($name, $prefix . 'core_tagmaps.resource_id = ' . $name . '.' . $primary, array())
		where ( $prefix . "core_tagmaps.resource_type = ?", $type )->where ( $prefix . "core_tagmaps.resource_id = ?", $subject->getIdentity () )->group ( $prefix . 'core_tags.text' );
		
		if ($where) {
			$select->where ( $where );
		}
		
		$rawData = $db->fetchAll ( $select );
		return $this->categorizeTags ( $rawData );
	}
	
	public function categorizeTags($rawData) {
		$tags = array ();
		
		foreach ( $rawData as $item ) {
			$tags [] = $this->defineTagClass ( $item );
		}
		
		return $tags;
	}
	
	public function defineTagClass($tag) {
		if (empty ( $tag ['freq'] )) {
			return $tag;
		}
		
		if ($tag ['freq'] <= 1) {
			$tag ['class'] = 1;
		} elseif ($tag ['freq'] <= 3) {
			$tag ['class'] = 2;
		} elseif ($tag ['freq'] <= 7) {
			$tag ['class'] = 3;
		} elseif ($tag ['freq'] <= 10) {
			$tag ['class'] = 4;
		} elseif ($tag ['freq'] <= 20) {
			$tag ['class'] = 5;
		} elseif ($tag ['freq'] <= 40) {
			$tag ['class'] = 6;
		} elseif ($tag ['freq'] <= 65) {
			$tag ['class'] = 7;
		} elseif ($tag ['freq'] <= 100) {
			$tag ['class'] = 8;
		} else {
			$tag ['class'] = 9;
		}
		
		return $tag;
	}
	
	public function rateObject($score, $object = null, $user = null) {
		if (! $object) {
			if (! Engine_Api::_ ()->core ()->hasSubject ()) {
				return null;
			}
			$object = Engine_Api::_ ()->core ()->getSubject ();
		}
		
		if (! $object->getIdentity ()) {
			return null;
		}
		
		if (! $user) {
			$user = Engine_Api::_ ()->user ()->getViewer ();
		}
		
		if (! ($object instanceof Core_Model_Item_Abstract) || ! ($user instanceof User_Model_User)) {
			return null;
		}
		
		if ($this->isRated ( $object, $user )) {
			return null;
		}
		
		$owner = $object->getOwner ();
		$owner_id = 0;
		if ($owner->getType () == 'user') {
			$owner_id = $owner->getIdentity ();
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'rates', 'kowcore' );
		$values = array ('score' => $score, 'user_id' => $user->getIdentity (), 'object_type' => $object->getType (), 'object_id' => $object->getIdentity (), 'owner_id' => $owner_id, 'creation_date' => date ( 'Y-m-d H:i:s' ), 'ip' => ip2long ( $_SERVER ['REMOTE_ADDR'] ) );
		
		$row = $table->createRow ();
		$row->setFromArray ( $values );
		$row->save ();
		
		return $row;
	}
	
	public function getRates($object = null, $userDetails = false) {
		if (! $object) {
			if (! Engine_Api::_ ()->core ()->hasSubject ()) {
				return false;
			}
			$object = Engine_Api::_ ()->core ()->getSubject ();
		}
		
		if (! ($object instanceof Core_Model_Item_Abstract)) {
			return null;
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'rates', 'kowcore' );
		$name = $table->info ( 'name' );
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $name )->where ( $name . '.object_type = ?', $object->getType () )->where ( $name . '.object_id = ?', $object->getIdentity () );
		
		if ($userDetails == true) {
			$userTable = Engine_Api::_ ()->getItemTable ( 'user' );
			$utname = $userTable->info ( 'name' );
			$select->joinInner ( $utname, $utname . '.user_id = ' . $name . '.user_id' );
			
			return $userTable->fetchAll ( $select );
		}
		
		return $table->fetchAll ( $select );
	}
	
	public function getFriends($viewer = null, $details = true) {
		if (! $viewer) {
			$viewer = Engine_Api::_ ()->user ()->getViewer ();
		}
		
		$table = Engine_Api::_ ()->getItemTable ( 'user' );
		$prefix = $table->getTablePrefix ();
		
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $prefix . 'users' )->joinLeft ( $prefix . 'user_membership', $prefix . 'user_membership.user_id = ' . $prefix . 'users.user_id', array () )->where ( $prefix . 'user_membership.resource_id = ?', $viewer->getIdentity () )->where ( $prefix . 'user_membership.resource_approved = 1' )->where ( $prefix . 'user_membership.user_approved = 1' );
		
		if ($details) {
			return Zend_Paginator::factory ( $select );
		}
		
		$data = $table->fetchAll ( $select );
		$uids = array ();
		foreach ( $data as $row ) {
			$uids [] = $row->getIdentity ();
		}
		
		return $uids;
	}
	
	public function getAllRates($type) {
		$type = strtolower ( trim ( $type ) );
		if (! $type) {
			return false;
		}
		
		$ctable = Engine_Api::_ ()->getItemTable ( $type );
		$cname = $ctable->info ( 'name' );
		$primary = array_shift ( $ctable->info ( 'primary' ) );
		
		$table = Engine_Api::_ ()->getDbTable ( 'rates', 'kowcore' );
		$name = $table->info ( 'name' );
		
		$select = $ctable->select ()->setIntegrityCheck ( false )->from ( $name, array ('score' => 'AVG(' . $name . '.score)' ) )->joinLeft ( $cname, $cname . '.' . $primary . '=' . $name . '.object_id' )->group ( $name . '.object_id' );
		
		return Zend_Paginator::factory ( $select );
	}
	
	public function getRateInfo($object = null) {
		if (! $object) {
			if (! Engine_Api::_ ()->core ()->hasSubject ()) {
				return false;
			}
			$object = Engine_Api::_ ()->core ()->getSubject ();
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'rates', 'kowcore' );
		$name = $table->info ( 'name' );
		
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $name, array ('score' => 'AVG(' . $name . '.score)', 'cnt' => 'COUNT(' . $name . '.rate_id)' ) )->where ( $name . '.object_id = ?', $object->getIdentity () )->where ( $name . '.object_type = ?', $object->getType () )->group ( $name . '.object_id' );
		
		return $table->fetchRow ( $select );
	}
	
	public function getRaters($object = null) {
		if (! $object) {
			if (! Engine_Api::_ ()->core ()->hasSubject ()) {
				return false;
			}
			$object = Engine_Api::_ ()->core ()->getSubject ();
		}
		
		$userTable = Engine_Api::_ ()->getItemTable ( 'user' );
		$uName = $userTable->info ( 'name' );
		
		$table = Engine_Api::_ ()->getDbTable ( 'rates', 'kowcore' );
		$name = $table->info ( 'name' );
		
		$select = $userTable->select ()->from ( $uName )->joinInner ( $name, $uName . '.user_id = ' . $name . '.user_id', array () )->where ( $name . '.object_type = ?', $object->getType () )->where ( $name . '.object_id = ?', $object->getIdentity () );
		
		return Zend_Paginator::factory ( $userTable->fetchAll ( $select ) );
	}
	
	public function isRated($object = null, $user = null, $ip = null) {
		if (! $user) {
			$user = Engine_Api::_ ()->user ()->getViewer ();
		}
		
		if (! $object) {
			if (! Engine_Api::_ ()->core ()->hasSubject ()) {
				return false;
			}
			$object = Engine_Api::_ ()->core ()->getSubject ();
		}
		
		if (! ($object instanceof Core_Model_Item_Abstract) || ! ($user instanceof User_Model_User)) {
			return null;
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'rates', 'kowcore' );
		$select = $table->select ()->where ( 'object_type = ?', $object->getType () )->where ( 'object_id = ?', $object->getIdentity () )->where ( 'user_id = ?', $user->getIdentity () );
		
		if ($user->getIdentity () == 0 && $ip !== null) {
			$ip = ( int ) $ip;
			$select->where ( 'ip = ?', $ip );
		}
		
		return ( bool ) $table->fetchRow ( $select );
	}
	
	public function getItemTypes() {
		$modules = array ('blog', 'album', 'video', 'poll', 'event', 'group', 'classified', 'contest', 'music', 'user' );
		$types = array ('blog', 'album', 'video', 'poll', 'event', 'group', 'classified', 'contest', 'music_playlist', 'user' );
		$labels = array ('blog' => 'Blogs', 'album' => 'Albums', 'video' => 'Videos', 'poll' => 'Polls', 'album_photo' => 'Album Photos', 'event' => 'Events', 'group' => 'Groups', 'classified' => 'Classifieds', 'contest' => 'Contests', 'music_playlist' => 'Music Playlists', 'user' => 'Users' );
		
		$manifest = Zend_Registry::get ( 'Engine_Manifest' );
		$installedModules = array_intersect ( $modules, array_keys ( $manifest ) );
		$data = array ();
		
		foreach ( $installedModules as $type ) {
			$data = array_merge ( $manifest [$type] ['items'], $data );
		}
		
		$data = array_intersect ( $data, $types );
		$result = array ();
		foreach ( $data as $type ) {
			$result [$type] = $labels [$type];
		}
		
		return $result;
	}
	
	public function getEventRSVPLink(Event_Model_Event $subject) {
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$row = $subject->membership ()->getRow ( $viewer );
		
		if (null === $row) {
			if ($subject->membership ()->isResourceApprovalRequired ()) {
				return array ('label' => 'Request Invite', 'icon' => 'application/modules/Event/externals/images/member/join.png', 'class' => 'smoothbox', 'route' => 'event_extended', 'params' => array ('controller' => 'member', 'action' => 'request', 'event_id' => $subject->getIdentity () ) );
			} else {
				return array ('label' => 'Join Event', 'icon' => 'application/modules/Event/externals/images/member/join.png', 'class' => 'smoothbox', 'route' => 'event_extended', 'params' => array ('controller' => 'member', 'action' => 'join', 'event_id' => $subject->getIdentity () ) );
			}
		} 

		else if ($row->active) {
			if (! $subject->isOwner ( $viewer )) {
				return array ('label' => 'Leave Event', 'icon' => 'application/modules/Event/externals/images/member/leave.png', 'class' => 'smoothbox', 'route' => 'event_extended', 'params' => array ('controller' => 'member', 'action' => 'leave', 'event_id' => $subject->getIdentity () ) );
			} else {
				return array ('label' => 'Delete Event', 'icon' => 'application/modules/Event/externals/images/delete.png', 'class' => 'smoothbox', 'route' => 'event_specific', 'params' => array ('action' => 'delete', 'event_id' => $subject->getIdentity () ) );
			}
		} 

		else if (! $row->resource_approved && $row->user_approved) {
			return array ('label' => 'Cancel Invite Request', 'icon' => 'application/modules/Event/externals/images/member/cancel.png', 'class' => 'smoothbox', 'route' => 'event_extended', 'params' => array ('controller' => 'member', 'action' => 'cancel', 'event_id' => $subject->getIdentity () ) );
		} 

		else if (! $row->user_approved && $row->resource_approved) {
			return array (array ('label' => 'Accept Event Invite', 'icon' => 'application/modules/Event/externals/images/member/accept.png', 'class' => 'smoothbox', 'route' => 'event_extended', 'params' => array ('controller' => 'member', 'action' => 'accept', 'event_id' => $subject->getIdentity () ) ), array ('label' => 'Ignore Event Invite', 'icon' => 'application/modules/Event/externals/images/member/reject.png', 'class' => 'smoothbox', 'route' => 'event_extended', 'params' => array ('controller' => 'member', 'action' => 'reject', 'event_id' => $subject->getIdentity () ) ) );
		}
		
		return false;
	}
	
	public function getGroupMembershipLink(Group_Model_Group $subject) {
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		
		if (! $viewer->getIdentity ()) {
			return false;
		}
		
		$row = $subject->membership ()->getRow ( $viewer );
		
		// Not yet associated at all
		if (null === $row) {
			if ($subject->membership ()->isResourceApprovalRequired ()) {
				return array ('label' => 'Request Membership', 'icon' => 'application/modules/Group/externals/images/member/join.png', 'class' => 'smoothbox', 'route' => 'group_extended', 'params' => array ('controller' => 'member', 'action' => 'request', 'group_id' => $subject->getIdentity () ) );
			} else {
				return array ('label' => 'Join Group', 'icon' => 'application/modules/Group/externals/images/member/join.png', 'class' => 'smoothbox', 'route' => 'group_extended', 'params' => array ('controller' => 'member', 'action' => 'join', 'group_id' => $subject->getIdentity () ) );
			}
		} 

		// Full member
		// @todo consider owner
		else if ($row->active) {
			if (! $subject->isOwner ( $viewer )) {
				return array ('label' => 'Leave Group', 'icon' => 'application/modules/Group/externals/images/member/leave.png', 'class' => 'smoothbox', 'route' => 'group_extended', 'params' => array ('controller' => 'member', 'action' => 'leave', 'group_id' => $subject->getIdentity () ) );
			} else {
				return array ('label' => 'Delete Group', 'icon' => 'application/modules/Group/externals/images/delete.png', 'class' => 'smoothbox', 'route' => 'group_specific', 'params' => array ('action' => 'delete', 'group_id' => $subject->getIdentity () ) );
			}
		} 

		else if (! $row->resource_approved && $row->user_approved) {
			return array ('label' => 'Cancel Membership Request', 'icon' => 'application/modules/Group/externals/images/member/cancel.png', 'class' => 'smoothbox', 'route' => 'group_extended', 'params' => array ('controller' => 'member', 'action' => 'cancel', 'group_id' => $subject->getIdentity () ) );
		} 

		else if (! $row->user_approved && $row->resource_approved) {
			return array (array ('label' => 'Accept Membership Request', 'icon' => 'application/modules/Group/externals/images/member/accept.png', 'class' => 'smoothbox', 'route' => 'group_extended', 'params' => array ('controller' => 'member', 'action' => 'accept', 'group_id' => $subject->getIdentity () ) ), array ('label' => 'Ignore Membership Request', 'icon' => 'application/modules/Group/externals/images/member/reject.png', 'class' => 'smoothbox', 'route' => 'group_extended', 'params' => array ('controller' => 'member', 'action' => 'reject', 'group_id' => $subject->getIdentity () ) ) );
		}
		
		return false;
	}

}